package com.sfac.springBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.swing.text.DateFormatter;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * personal demo
 **/
@WebListener
public class LoginFileDestroyListener implements ServletContextListener {

    private static final Logger LOGGER= LoggerFactory.getLogger(LoginFileDestroyListener.class);

    private static final String baseFolder="/var/log";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("contextInitialized");

        //删除非今日的日志文件
        File desFolder = new File(baseFolder);
        if(!desFolder.exists()){
            return;
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String cur = dateTimeFormatter.format(LocalDateTime.now());

        File[] files = desFolder.listFiles();
        for (File f:files){
            if(!f.getName().contains(cur)){
                f.delete();
            }
        }


    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("contextDestroyed");

    }
}
